package com.bodu.global.config.filter;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.bodu.core.entity.result.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 言曌
 * @date 2018/5/4 下午12:36
 */
@Component
public class KaptchaAuthenticationFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 判断session当中的验证码 与 用户输入的验证码是否一致
        // 如果不加判断，它会过滤全部的请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

        if (uri.contains("/login/in")) {
            String sessionCode = (String) request.getSession().getAttribute("captcha");

            String userCode = request.getParameter("validCode");

            if (StringUtils.isEmpty(userCode)) {
                Result re  = Result.fail("验证码不能为空");
                setResponseData(re,response);
            } else {
                if (!sessionCode.equalsIgnoreCase(userCode)) {
                    Result re  = Result.fail("验证码有误!");
                    setResponseData(re,response);
                } else {
                    filterChain.doFilter(request, response);
                }
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 返回数据
     * @param result
     * @param response
     * @throws IOException
     */
    private void setResponseData(Result result, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONObject.toJSON(result));
        response.getWriter().flush();
    }
}
